﻿using Cherry.Agile.Security;
using Cherry.Agile.UI.Framework.Security;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.SessionState;
using System.Web.Mvc;
using Cherry.Agile.Mvc;

namespace Cherry.Agile.Web.Areas.Admin.Controllers
{
    public class AuthController : Controller
    {
        
        string Code
        {
            get
            {
                var obj = base.Session["verifyCode"];
                if (obj == null)
                    return string.Empty;
                return obj.ToString();
            }
            set
            {
                Session["verifyCode"] = value;
            }
        }

        // GET: Admin/Auth
        public ActionResult Login()
        {
            if(User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.Forcescript = "";
                return View();
            }

        }

        [HttpPost]
        [AuthorizeIgnore]
        public ActionResult Login(string username, string password, string verifyCode, bool IsRemeberMe)
        {
            if(!Validate(verifyCode))
            {
                ModelState.AddModelError("verifycode", "验证码错误");
                return View();
            }
            
            var ticket = new Agile.Security.AccountTicket() { Identity = username, Password = password, Type = 1 };
            //if(!Cherry.Agile.UI.Framework.Security.AuthorizationManager.Login(ticket,true))
            //{
            //    ModelState.AddModelError("error", "用户名或密码错误");
            //    return View();
            //}
            //else
            //{
            return RedirectToAction("Index", "Default");
            //}

        }



        [HttpPost]
        [AuthorizeIgnore]
        public ActionResult Register(string email, string Identity, string Password)
        {
            return RedirectToAction("Login");
        }

        [HttpPost]
        [AuthorizeIgnore]
        public ActionResult Send(string email)
        {
            return RedirectToAction("Login");
        }

        private bool Validate(string code)
        {
            return string.Compare(code, Code.Replace(" ", ""), true) == 0;
        }

        [AuthorizeIgnore]
        public virtual ActionResult VerifyImage()
        {
            var validateCodeType = new ValidateCode_Style10();
            string code = "6666";
            byte[] bytes = validateCodeType.CreateImage(out code);
            //this.CookieContext.VerifyCodeGuid = VerifyCodeHelper.SaveVerifyCode(code);
            Code = code;
            return File(bytes, @"image/jpeg");
        }

    }
}